import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from '@/config';
import { prepareConnection } from '@/db';
import { User } from '@/db/entity';
import { EXCEPTION_USER } from '@/pages/api/config/codes';
import { ISession } from '..';

const detail = async (req: NextApiRequest, res: NextApiResponse) => {
  const session: ISession = req.session
  const db = await prepareConnection()
  const userRepo = db.getRepository(User)

  const user = await userRepo.findOne({
    where: {
      id: session.userId
    }
  })

  if (!user) {
    res?.status(200)?.json({
      ...EXCEPTION_USER.NOT_FOUND
    })
    return
  }

  res?.status(200).json({
    code: 200,
    msg: 'success',
    data: user
  })
}

export default withIronSessionApiRoute(detail, ironOptions);